#include <intrins.h>
#include "Reg52.h"
#include "types.h"
#include "smi.h"
#include "uart.h"
#include "cmd.h"
#include "net.h"

void msdelay(unsigned ms)
{
	unsigned t;
	while (ms--) {
		t = 143;
		while (t--);
	}
}

void timer_init(void)
{
	unsigned char br_cnt = 0xfd;
	/* -------------initialize Timer 0 -----------------------------*/

	ET0=0;  // enable timer 0 interrupt
	TH0=0;
	TL0=0; // timer 0 counter
	TF0=0; // timer 1 flag

	/* -------------initialize Timer 1 -----------------------------*/
	ET1 = 0;  // disable timer 1 interrupt
	TH1 = br_cnt;
	TL1 = br_cnt; // timer 1 counter
	TF1 = 0; // timer 1 flag

	// setup Timer mode
	TMOD=0x21;  // set timer 1 as timer(1) , timer 0 as counter(5)

	//PCA
	CMOD = 0x86;
	CCON = 0x00;
	CL = 0;
	CH = 0;

	//CCAP0L = 0x00;
	//CCAP0H = 0x06;
	CCAP0L = 0x02;
	CCAP0H = 0x00;
//	CCAPM0 = 0x49;
	CCAPM0 = 0x00;
	CCAPM1 = 0x00;
//	CCAPM2 = 0x00;
//	CCAPM3 = 0x00;

	EPCA_LVD = 1;

	// enable/disable timer
	TR0=0;  // disable timer 0
	TR1=1;  // disable timer 1

	CR = 1;
}

void mcu_init(void)
{
	EA = 0;
	timer_init();
	uart_init();
	EA = 1;
}

#define	PORT_HI(io, p)		(io |=  (1 << p))
#define	PORT_LO(io, p)		(io &= ~(1 << p))
#define	RESET_OUTPUT		do {(P1M0 &= ~(1 << 1));(P1M1 &= ~(1 << 1));} while (0)
#if 0
static void chip_hardware_reset(void)
{
	/* set RESET PIN output */
	RESET_OUTPUT;
	PORT_LO(P1, 1);
	msdelay(20);
	PORT_HI(P1, 1);
}
#endif

void main(void)
{
	uint16_t value;
	uint16_t count;

	mcu_init();
	smi_init();

	value = P1;
	uart_send_byte(value);
	value = P1M0;
	uart_send_byte(value);
	value = P1M1;
	uart_send_byte(value);

	value = P2;
	uart_send_byte(value);
	value = P2M0;
	uart_send_byte(value);
	value = P2M1;
	uart_send_byte(value);

	vlan_init(RTL8309SCR);
	vlan_init(RTL8309SCL);
	vlan_init(RTL8309SB);
	vlan_default();

	while (1) {
		polling_uart();
		msdelay(100);
	}
}

